package com.huanxing.cloud.mall.api.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.mall.api.mapper.OrderItemMapper;
import com.huanxing.cloud.mall.api.mapper.OrderRefundMapper;
import com.huanxing.cloud.mall.api.service.IOrderRefundService;
import com.huanxing.cloud.mall.common.entity.OrderItem;
import com.huanxing.cloud.mall.common.entity.OrderRefund;
import com.huanxing.cloud.mall.common.enums.OrderItemEnum;
import com.huanxing.cloud.mall.common.enums.OrderRefundEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商城退款单
 *
 * @author lijx
 * @date 2022/5/31
 */
@Service
@AllArgsConstructor
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund>
    implements IOrderRefundService {
  private final OrderItemMapper orderItemMapper;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean saveRefund(OrderRefund orderRefund) {
    OrderItem orderItem = orderItemMapper.selectById(orderRefund.getOrderItemId());
    if (ObjectUtil.isNull(orderItem)) {
      throw new RuntimeException("子订单不存在");
    }
    // 只有正常订单可申请退款
    if (OrderItemEnum.STATUS_0.getCode().equals(orderItem.getStatus())) {
      if (OrderRefundEnum.STATUS_1.getCode().equals(orderRefund.getStatus())) {
        orderItem.setStatus(OrderItemEnum.STATUS_1.getCode());
      } else if (OrderRefundEnum.STATUS_2.getCode().equals(orderRefund.getStatus())) {
        orderItem.setStatus(OrderItemEnum.STATUS_2.getCode());
      } else {
        throw new RuntimeException("退款状态错误");
      }
      orderRefund.setRefundAmount(orderItem.getPayPrice());
      orderRefund.setArrivalStatus(CommonConstants.NO);
      orderRefund.setOrderId(orderItem.getOrderId());
      baseMapper.insert(orderRefund);
      orderItemMapper.updateById(orderItem);
    }
    return true;
  }
}
